<template>
  <view class="list">
    <!-- 顶部提示框：动态显示更新数量 -->
    <view class="tips" :class="{ 'tips-ani': tipShow }"
      >为您更新了{{ updateCount }}条商品数据</view
    >

    <!-- 商品列表：添加加载中占位 -->
    <uni-list v-if="tableData && tableData.length > 0">
      <uni-list-item
        :border="true"
        class="uni-list-item--waterfall"
        v-for="item in tableData"
        :key="item.id"
        :to="
          '/pages/goods/goodsDetail/goodsDetail?id=' +
          item.id +
          '&title=' +
          item.name
        "
      >
        <template v-slot:header>
          <view class="uni-thumb shop-picture">
            <!-- 图片添加默认占位 -->
            <image
              :src="item.mainImage || '/static/images/default-goods.png'"
              mode="aspectFill"
              @error="
                (e) => (e.target.src = '/static/images/default-goods.png')
              "
            ></image>
          </view>
        </template>
        <template v-slot:body>
          <view class="shop">
            <view>
              <view class="uni-title">
                <text class="uni-ellipsis-2">{{
                  item.name || "未知商品"
                }}</text>
              </view>
            </view>
            <view class="button-box">
              <view class="shop-price">
                <text>¥</text>
                <text class="shop-price-text">{{
                  item.displayPrice || 0
                }}</text>
                <!-- <text>.00</text> -->
              </view>
              <view class="shop-buy" @tap="goBuy(item)"> 立即购买</view>
            </view>
          </view>
        </template>
      </uni-list-item>
    </uni-list>

    <!-- 空状态提示 -->
    <view v-else-if="!loading" class="empty-tip">暂无商品数据</view>

    <!-- 加载中提示 -->
    <view v-else class="loading-tip">加载中...</view>

    <!-- 上拉加载组件 -->
    <uni-load-more
      v-if="options.status !== 'more'"
      :status="options.status"
      margin-top="20rpx"
    />
  </view>
</template>

<script>
import { tableData } from "./db_init.json";
import { getProductList } from "@/services/goods.js";
export default {
  components: {},
  data() {
    return {
      collection: "opendb-mall-goods",
      field:
        "goods_thumb,name,goods_tip,tag,goods_price,comment_count,month_sell_count,shop_name",
      tipShow: false,
      tableData: null, // 初始为null（区分空数据）
      loading: false, // 加载中状态
      updateCount: 0, // 实际更新数量
      options: {
        status: "more", // more:可加载, loading:加载中, noMore:无更多
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  onLoad() {
    // 初始加载：先显示本地数据，再请求接口更新（优化体验）
    // this.tableData = tableData;
    this.initGoodsListData();
  },
  methods: {
    // 加载数据（支持首次加载/下拉刷新/上拉加载）
    async initGoodsListData(isLoadMore = false) {
      // 上拉加载时标记状态
      if (isLoadMore) {
        this.options.status = "loading";
      } else {
        this.loading = true; // 首次/刷新时显示加载中
      }

      try {
        const res = await getProductList({
          pageNum: this.options.pageNum,
          pageSize: this.options.pageSize,
        });

        const newData = res.rows || [];
        console.log(222, newData);
        
        // 处理数据：首次/刷新→覆盖，上拉→追加
        if (isLoadMore) {
          this.tableData = [...this.tableData, ...newData];
        } else {
          // 计算更新数量（对比本地数据与接口数据）
          this.updateCount = newData.length;
          this.tableData = newData;
          // 显示提示框（3秒后隐藏）
          if (this.updateCount > 0) {
            this.tipShow = true;
            setTimeout(() => (this.tipShow = false), 3000);
          }
        }

        // 更新分页状态：无更多数据时标记
        this.options.status =
          newData.length < this.options.pageSize ? "noMore" : "more";
      } catch (err) {
        console.error("商品数据加载失败：", err);
        uni.showToast({ title: "加载失败", icon: "none" });
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh(); // 无论成功失败，停止下拉刷新
      }
    },

    // 立即购买：统一用 _id 跳转
    goBuy(item) {
              console.log(123,item);

      if (!item?.id) {
        
        uni.showToast({ title: "商品信息异常", icon: "none" });
        return;
      }
      uni.navigateTo({
        url: `/pages/goods/goodsDetail/goodsDetail?id=${item.id}&title=${
          item.name || "商品详情"
        }`,
      });
    },

    // 上拉加载更多
    loadMore() {
      // 避免重复加载
      if (this.options.status !== "more" || this.loading) return;
      this.options.pageNum += 1; // 页码自增
      this.initGoodsListData(true); // 标记为上拉加载
    },
  },

  // 下拉刷新：重置页码，重新加载第一页
  onPullDownRefresh() {
    this.options.pageNum = 1;
    this.options.status = "more";
    this.initGoodsListData();
  },

  // 上拉加载：调用加载更多方法
  onReachBottom() {
    this.loadMore();
  },
};
</script>

<style lang="scss">
// 页面背景色
page {
  background-color: #efeff4;
  min-height: 100%;
}

.tips {
  color: #67c23a;
  font-size: 14px;
  line-height: 40px;
  text-align: center;
  background-color: #f0f9eb;
  height: 0;
  opacity: 0;
  transform: translateY(-100%);
  transition: all 0.3s;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999; // 确保在顶部显示
}

.tips-ani {
  transform: translateY(0);
  height: 40px;
  opacity: 1;
}

// 商品列表样式
.uni-list-item--waterfall {
  padding: 15rpx;
  background-color: #fff;
  margin-bottom: 15rpx;
  border-radius: 10rpx;
}

.shop {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-left: 15rpx;
}

.shop-picture {
  width: 220rpx;
  height: 220rpx;
  border-radius: 8rpx;
  overflow: hidden; // 图片圆角裁剪
}

.shop-picture image {
  width: 100%;
  height: 100%;
}

.uni-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.button-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10rpx;
}

.shop-price {
  font-size: 28rpx;
  color: #ff5a5f;
}

.shop-price-text {
  font-size: 36rpx;
  font-weight: bold;
}

.shop-buy {
  width: 180rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #27ba9b;
  color: #fff;
  text-align: center;
  border-radius: 30rpx;
  font-size: 28rpx;
}

// 空状态/加载中提示
.empty-tip,
.loading-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 30rpx;
}
</style>
